
import 'dart:async';
import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_base_app/base/base_page.dart';
import 'package:flutter_base_app/base/base_page_view_model.dart';
import 'package:flutter_base_app/utils/file_utils.dart';
import 'package:flutter_video_info/flutter_video_info.dart';

import '../widgets/video_player.dart';

class PageVideoCompress3 extends StatefulWidget {
  const PageVideoCompress3({super.key});

  @override
  State<PageVideoCompress3> createState() => _State();
}

class _State extends BasePageState<BasePageViewModel, PageVideoCompress3> {

  @override
  BasePageViewModel createViewModel() {
    return BasePageViewModel();
  }

  @override
  Widget buildContent(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Compressor Sample 3'),
      ),
      body: Container(
        margin: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            if (_filePath != null)
              Text(
                'Original size: ${_filePath}',
                style: const TextStyle(fontSize: 16),
              ),
            const SizedBox(height: 8),
            if (_isVideoCompressed)
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    'Size after compression: ${_desFile}',
                    style: const TextStyle(fontSize: 16),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    'Duration: $_duration seconds',
                    style: const TextStyle(fontSize: 16, color: Colors.red),
                  ),
                ],
              ),
            const SizedBox(height: 16),
            Visibility(
              visible: !_isVideoCompressed,
              child: StreamBuilder<double>(
                stream: progressStream,
                builder: (BuildContext context,
                    AsyncSnapshot<dynamic> snapshot) {
                  if (snapshot.data != null && snapshot.data > 0) {
                    return Column(
                      children: <Widget>[
                        LinearProgressIndicator(
                          minHeight: 8,
                          value: snapshot.data / 100,
                        ),
                        const SizedBox(height: 8),
                        Text(
                          '${snapshot.data.toStringAsFixed(0)}%',
                          style: const TextStyle(fontSize: 20),
                        )
                      ],
                    );
                  }
                  return const SizedBox.shrink();
                },
              ),
            ),
            const SizedBox(height: 24),
            if (_displayedFile != null)
              Builder(
                builder: (BuildContext context) => Container(
                  alignment: Alignment.center,
                  child: OutlinedButton(
                      onPressed: () => Navigator.push<dynamic>(
                        context,
                        MaterialPageRoute<dynamic>(
                          builder: (_) => VideoPlayerScreen(_desFile),
                        ),
                      ),
                      child: const Text('Play Video')),
                ),
              ),
            Text(
              _failureMessage ?? '',
            )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () => _pickVideo(),
        label: const Text('Pick Video'),
        icon: const Icon(Icons.video_library),
        backgroundColor: const Color(0xFFA52A2A),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    progressController = StreamController<double>();
    progressStream = progressController.stream;
    _subscription = FlutterVideoInfo.progressStream.listen((progress) {
      progressController.sink.add(progress*100);
    });
  }

  @override
  void dispose() {
    super.dispose();
    _subscription.cancel();
  }

  late StreamSubscription _subscription;
  late StreamController<double> progressController;
  late Stream<double> progressStream;

  bool _isVideoCompressed = false;
  String? _displayedFile;
  late int _duration;
  String? _failureMessage;
  String? _filePath;

  String _desFile = "";

  Future<void> _pickVideo() async {
    _isVideoCompressed = false;

    final FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.video,
    );

    final PlatformFile? file = result?.files.first;

    if (file == null) {
      return;
    }

    _filePath = file.path;

    setState(() {
      _failureMessage = null;
    });

    final Stopwatch stopwatch = Stopwatch()..start();

    final path = await FlutterVideoInfo.compressVideo(_filePath!);

    stopwatch.stop();
    final Duration duration =
    Duration(milliseconds: stopwatch.elapsedMilliseconds);
    _duration = duration.inSeconds;

    if (path != null) {
      setState(() {
        _desFile = path;
        _displayedFile = _desFile;
        _isVideoCompressed = true;
      });
    } else  {
      setState(() {
        _failureMessage = "fail null";
      });
    }
  }

}

